import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const path = require('path');
const ini = require('ini');
const iconv = require('iconv-lite');
const fs = require('fs');
const glob = require('glob'); // 遍历文件夹
const ncp = require('ncp').ncp;
const jschardet = require('jschardet');
var cp = require("child_process");

let resourcesUrl = '' // 软件安装目录下的/resources路径
const getResourcesUrl = () => {
  // 文件下载存放位置
  let downloadsFolder = ''
  if (!syncOperationWindow('isPackaged')) {
    downloadsFolder = process.cwd()
  } else {
    downloadsFolder = path.parse(syncOperationWindow('getAppPath')).dir
  }
  resourcesUrl = downloadsFolder
  return resourcesUrl
}

// 复制文件
function copyFiles(source, destination) {
  ncp(source, destination, (ncpErr) => {
    if (ncpErr) {
      return console.error('复制文件时发生错误:', ncpErr);
    }
    console.log('文件复制成功！');
  });
}

// 删除文件夹
const deleteFolder = (folderPath) => {
  if (!fs.existsSync(folderPath)) {
    console.log('Folder does not exist, nothing to delete.');
    return;
  }

  // 读取文件夹内容并递归删除
  fs.readdirSync(folderPath).forEach((file) => {
    const curPath = path.join(folderPath, file);
    if (fs.lstatSync(curPath).isDirectory()) {
      // 递归删除子文件夹
      deleteFolder(curPath);
    } else {
      // 删除文件
      fs.unlinkSync(curPath);
    }
  });

  // 删除文件夹自身
  fs.rmdirSync(folderPath);
};

const inifun = (iniUrl) => {
  const str = fs.readFileSync(iniUrl);
  const iniContent = iconv.decode(str, 'GBK');
  const iniObject = ini.parse(iniContent);
  return iniObject
}

// 修改文本内容
const fun = (iniUrl, iniObject, isBool = true) => {
  // 序列化INI配置
  let s = isBool ? ini.stringify(iniObject) : iniObject;
  // 将INI内容转换为GBK编码并写入文件
  let gbkBuffer = iconv.encode(s, 'gbk');
  fs.writeFileSync(iniUrl, gbkBuffer);
}

const getBianliangUrl = (config) => {
  return path.join(path.dirname(config.versionPath), 'bianliangVal.ini')
}

let lastZhucheng_code = ''; // 记录上一次的主城代码

const operationWindow = (actionType, other = {}) => ipcRenderer.send('operation-window', actionType, other)

const syncOperationWindow = (actionType, other = {}) => ipcRenderer.sendSync('operation-window', actionType, other)

// Custom APIs for renderer
const api: any = {
  operationWindow,
  syncOperationWindow,
  copePath: (text) => {
    operationWindow('copyToClipboard', {
      text
    })
  },
  getLocalMirserverPath: (isRar = false) => {
    if (isRar) {
      return path.join(getResourcesUrl(), 'Mirserver.rar')
    }
    return path.join(getResourcesUrl(), 'Mirserver')
  },
  openApp: (type) => {
    cp.execFile(path.join(getResourcesUrl(), 'app', type, `${type}.exe`), [], function (err, stdout, stderr) {
      if (err) {
        console.error(err);
      }
      console.log("stdout:", stdout)
      console.log("stderr:", stderr);
    });
  },
  getVal: (..._path) => {
    return new Promise((resolve) => {
      const str = fs.readFileSync(path.join(..._path)).toString();
      resolve(str)
    })
  },
  openMirserver: (...file) => {
    const url = path.join(getResourcesUrl(), 'Mirserver', ...file)
    operationWindow('openPath', { url })
  },
  openFile: (config, ...file) => {
    const url = path.join(config.path1, "Mir200", 'Envir', ...file);
    operationWindow('openPath', { url })
  },
  openFile2: (config, ...file) => {
    const url = path.join(config.path1, ...file);
    operationWindow('openPath', { url })
  },
  getBagPath: (url) => {
    const p1 = path.dirname(url); // 获取上一级
    return path.join(p1, '大背包');
  },
  openMapInfo: (config) => {
    return new Promise(() => {
      // let newContent = config.mapVal.replace(new RegExp('主城代码', 'g'), config.zhucheng_code);
      api.copePath(config.mapVal)
      api.openFile(config, 'MapInfo.txt')
      // fs.rename(pathToFile, newPathToFile, function () { })
    })

  },
  getBianLiangVal: (config) => {
    const iniUrl = config.versionPath ? getBianliangUrl(config) : ''
    const iniUrl2 = path.join(api.getLocalMirserverPath(), 'bianliangVal.ini')

    try {
      const iniContent = fs.readFileSync(iniUrl).toString();
      const iniObject = ini.parse(iniContent);
      return iniObject
    } catch (error) {
      const iniContent = fs.readFileSync(iniUrl2).toString();
      const iniObject = ini.parse(iniContent);
      return iniObject
    }
  },
  duQuMir: (config) => {
    return new Promise((resolve) => {
      // ----控制器----
      const iniUrl = path.join(config.path, 'Config.ini')
      const iniObject = inifun(iniUrl)

      iniObject?.GameConf?.DynamicIPMode && (iniObject.GameConf.DynamicIPMode = '1'); // 动态ip: 1开启  0关闭
      iniObject?.GameConf?.UseAccessDB && (iniObject.GameConf.UseAccessDB = '1'); // 是否使用Access数据库: 1开启  0关闭
      iniObject?.GameConf?.GameName && (iniObject.GameConf.GameName = config.name); // 游戏服务器名称
      iniObject?.GameConf?.GameDirectory && (iniObject.GameConf.GameDirectory = config.path + '\\'); // 游戏服务端所在目录
      iniObject?.GameConf?.AccessFileName && (iniObject.GameConf.AccessFileName = path.join(config.path, 'Mud2', 'DB', 'HeroDB.MDB')); // Access数据库路径，`${游戏服务端所在目录}\Mud2\DB\HeroDB.MDB`
      iniObject?.GameConf?.SqliteDBName && (iniObject.GameConf.SqliteDBName = path.join(config.path, 'Mud2', 'DB', 'GEEM2.db'))

      iniObject?.BackUp_DBServer?.SaveDirectory && (iniObject.BackUp_DBServer.SaveDirectory = path.join(config.path, '数据备份', 'DBServer', 'FDB') + '\\')
      iniObject?.BackUp_LoginSrv?.SaveDirectory && (iniObject.BackUp_LoginSrv.SaveDirectory = path.join(config.path, '数据备份', 'LoginSrv', 'IDDB') + '\\')
      iniObject?.BackUp_M2Server?.SaveDirectory && (iniObject.BackUp_M2Server.SaveDirectory = path.join(config.path, '数据备份', 'Envir', 'UserData') + '\\')
      iniObject?.BackUp_M2Server_GuildBase?.SaveDirectory && (iniObject.BackUp_M2Server_GuildBase.SaveDirectory = path.join(config.path, '数据备份', 'GuildBase') + '\\')
      iniObject?.BackUp_M2Server_Castle?.SaveDirectory && (iniObject.BackUp_M2Server_Castle.SaveDirectory = path.join(config.path, '数据备份', 'Castle') + '\\')

      iniObject?.LoginGate?.GatePort && (iniObject.LoginGate.GatePort = config.port); // 登录网关 - 服务器端口1
      iniObject?.SelGate?.GatePort && (iniObject.SelGate.GatePort = config.port + 10); // 角色网关 - 服务器端口1
      iniObject?.SelGate?.GatePort1 && (iniObject.SelGate.GatePort1 = config.port + 20); // 角色网关 - 服务器端口2
      iniObject?.RunGate?.GatePort1 && (iniObject.RunGate.GatePort1 = config.port + 30); // 游戏网关 - 服务器端口1
      iniObject?.RunGate?.GatePort2 && (iniObject.RunGate.GatePort2 = config.port + 40); // 游戏网关 - 服务器端口2
      iniObject?.LoginServer?.GatePort && (iniObject.LoginServer.GatePort = config.port + 50); // 游登录服务器 - 连接端口
      iniObject?.LoginServer?.ServerPort && (iniObject.LoginServer.ServerPort = config.port + 60); // 游登录服务器 - 通讯端口
      iniObject?.DBServer?.GatePort && (iniObject.DBServer.GatePort = config.port + 70); // 数据库服务器 - 连接端口
      iniObject?.DBServer?.ServerPort && (iniObject.DBServer.ServerPort = config.port + 80); // 数据库服务器 - 通讯端口
      iniObject?.LogServer?.Port && (iniObject.LogServer.Port = config.port + 90); // 游戏日志服务器端口
      iniObject?.M2Server?.GatePort && (iniObject.M2Server.GatePort = config.port + 100); // 游戏引擎服务器 - 连接端口
      iniObject?.M2Server?.MsgSrvPort && (iniObject.M2Server.MsgSrvPort = config.port + 110); // 游戏引擎服务器 - 通讯端口

      fun(iniUrl, iniObject)  

      // ----控制器e----

      // ----!setup----
      const iniUrl2 = path.join(config.path, 'Mir200', '!Setup.txt')
      const iniObject2 = inifun(iniUrl2)

      iniObject2.Share.ChatDir = path.join(config.path, 'Mir200', 'ChatLog') + '\\'
      iniObject2.Share.KickDummyIPList = path.join(config.path, 'Mir200', 'Envir', 'QuestDiary', 'KickIP.txt')

      iniObject2.Setup.KickDummyIPList = path.join(config.path, 'Mir200', 'Envir', 'QuestDiary', 'KickIP.txt')

      fun(iniUrl2, iniObject2)
      // ----!setup----

      // ----esp配置----
      const iniUrl3 = path.join(config.path, 'Mir200', 'esp配置.ini')
      const iniObject3 = inifun(iniUrl3)

      iniObject3.配置.大背包存放目录 = config.bagPath

      fun(iniUrl3, iniObject3)

      try {
        fs.mkdirSync(config.bagPath, { recursive: true });
        console.log('目录创建成功');
      } catch (error) {
        console.error('创建目录失败', error);
      }
      // ----esp配置----

      resolve(true)
    })
  },
  weiduan: (config) => {
    return new Promise((resolve) => {
      if (config.name) {
        const files = fs.readdirSync(path.join(config.path, "UpdateGate"));
        // 修改微端.exe文件名
        files.forEach(file => {
          if (file.includes('.exe')) {
            const pathToFile = path.join(config.path, "UpdateGate", file)
            const newPathToFile = path.join(config.path, "UpdateGate", `${config.name}.exe`)
            fs.rename(pathToFile, newPathToFile, function () { })
          }
        });

        const files2 = fs.readdirSync(path.join(config.path, "UpdateServer"));
        files2.forEach(file => {
          if (file.includes('.exe')) {
            const pathToFile = path.join(config.path, "UpdateServer", file)
            const newPathToFile = path.join(config.path, "UpdateServer", `${config.name}.exe`)
            fs.rename(pathToFile, newPathToFile, function (err) {
            })
          }
        });
      }

      if (config.port) {
        const url1 = path.join(config.path, 'UpdateGate', '!serverinfo.txt')
        const str = `${config.ip}:${config.port}`;
        let gbkBuffer = iconv.encode(str, 'gbk');
        fs.writeFileSync(url1, gbkBuffer);


        const url2 = path.join(config.path, 'UpdateGate', 'UpdateGate.ini')
        const iniObject1 = inifun(url2)
        iniObject1.Setup.ServerPort = config.port + 1
        iniObject1.Setup.GatePort = config.port + 2
        fun(url2, iniObject1)

        var lastChar = config.MirFilePath.charAt(config.MirFilePath.length - 1);
        console.log(lastChar, 'lastCharlastChar')
        if (lastChar !== '\\') {
          config.MirFilePath = config.MirFilePath + '\\'
        }

        const url3 = path.join(config.path, 'UpdateServer', 'Config.ini')
        const iniObject2 = inifun(url3)
        iniObject2.Setup.ServerHost = config.ip
        iniObject2.Setup.ServerPort = config.port
        iniObject2.Setup.GatePort = config.port + 1
        iniObject2.Setup.MirFilePath = config.MirFilePath
        iniObject2.Setup.Resources = config.Resources
        fun(url3, iniObject2)
      }


      const str2 = fs.readFileSync(path.join(config.pakUrl));
      const iniContent = iconv.decode(str2, 'GBK');
      const key = iniContent.split('\r\n')[3].split(config.Resources)[0]
      const newM = iniContent.split('\r\n').map(item => {
        return item.replace(key, config.MirFilePath);
      }).join('\r\n')
      let gbkBuffer = iconv.encode(newM, 'gbk');
      fs.writeFileSync(path.join(config.path, 'UpdateServer', 'Pak.txt'), gbkBuffer);

      resolve(true)
    })
  },
  tihuan: (config) => {
    return new Promise((resolve) => {
      // 要搜索的文件夹路径
      const folderPath = config.path + '/**/*';
      // 要搜索的文件扩展名
      const fileExtension = '.txt';
      // 要搜索的文本内容
      const searchText = config.v1;
      // 替换成的新文本内容
      const replaceText = config.v2;

      // 递归搜索文件夹中所有文本文件，并替换文本内容
      const files = glob.globSync(folderPath + fileExtension, {});
      files.forEach(function (file) {
        // 读取文件内容
        let data = fs.readFileSync(file);
        // 将文本内容进行替换

        const encoding = jschardet.detect(data).encoding;
        let content = ''
        if (encoding === 'GB2312') {
          content = iconv.decode(data, 'GBK');
        } else {
          content = data.toString()
        }
        fs.chmodSync(file, '700'); // 修改成全员读写权限
        // 将替换后的内容写回文件
        let newContent = content.replace(new RegExp(searchText, 'g'), replaceText);
        fs.writeFileSync(file, encoding === 'GB2312' ? iconv.encode(newContent, 'GBK') : newContent);
      });

      resolve(true)
    })
  },
  saveBianliang: (config) => {
    let s = ini.stringify(config.bianliangEnum);
    const iniUrl = getBianliangUrl(config)
    fs.writeFile(iniUrl, s, (err) => {
      if (err) throw err;
      console.log('文件已保存');
    });
  },
  tihuanBianliang: (config, callback) => {
    return new Promise((resolve) => {
      if (!config.versionPath || !config.path) {
        return callback?.(false)
      }
      // 递归搜索文件夹中所有文本文件，并替换文本内容
      const files = glob.globSync(`${config.path}/**/*.txt`, {});
      files.forEach(function (file, i) {
        // 读取文件内容
        let data = fs.readFileSync(file);
        // 将文本内容进行替换

        const encoding = jschardet.detect(data).encoding;
        let content = ''
        if (encoding === 'GB2312') {
          content = iconv.decode(data, 'GBK');
        } else {
          content = data.toString()
        }
        fs.chmodSync(file, '700'); // 修改成全员读写权限

        Object.keys(config.bianliangEnum).forEach(key => {
          const item = config.bianliangEnum[key]
          let escapedPattern = `${item.key}|${key}`.replace(/[\[\]\$\\]/g, '\\$&');
          content = content.replace(new RegExp(escapedPattern, 'ig'), item.val);
          if (item.inPutString) {
            const InPutString = `InPutString${key.slice(1)}`
            content = content.replace(new RegExp(`${InPutString}-替换变量|${InPutString}`, 'ig'), `InPutString${item.val.slice(1)}`);
          }
          if (item.inPutInteger) {
            const InPutInteger = `InPutInteger${key.slice(1)}`
            content = content.replace(new RegExp(`${InPutInteger}-替换变量|${InPutInteger}`, 'ig'), `InPutInteger${item.val.slice(1)}`);
          }
        })
        // 将替换后的内容写回文件
        fs.writeFileSync(file, encoding === 'GB2312' ? iconv.encode(content, 'GBK') : content);
        if (files.length === (i + 1)) {
          console.log('最后一条', file);
          callback?.(true)
        }
      });

      resolve(true)
    })
  },
  delCacheBianliang: (config, callback) => {
    return new Promise((resolve) => {
      if (!config.versionPath || !config.path) {
        return callback?.(false)
      }
      fs.unlink(getBianliangUrl(config), (err) => {
        if (err) throw err;
        console.log('文件已成功删除');
        return callback?.(true)
      });
      resolve(true)
    })
  },
  huiyuan: (config) => {
    return new Promise((resolve) => {
      if (config.zhucheng_code !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, "步骤1", '放入Market_Def');
        // 目标文件夹
        const destinationFolder = path.join(config.path1, "Mir200", 'Envir', 'Market_Def');

        // 先删除
        deleteFolder(path.join(destinationFolder, '微信礼包'))
        deleteFolder(path.join(destinationFolder, '新人接待'))
        // setTimeout(() => {
        // 在复制
        copyFiles(sourceFolder, destinationFolder)
        // }, 1000)

        setTimeout(() => {
          // 修改文件名中的主城代码
          const files = glob.globSync(destinationFolder + `/**/*-主城代码.txt`, {});
          files.forEach(function (file) {
            // const temp1 = file.split('/')
            // const name = temp1[temp1.length - 1].split('.txt')[0].split('-')[1]
            fs.rename(file, file.replace(`主城代码.txt`, `${config.zhucheng_code}.txt`), function () { })
          });
        }, 1500)

        resolve(true)
      }
      resolve(false)
      // fs.rename(pathToFile, newPathToFile, function () { })
    })
  },
  huiyuan2: (config) => {
    return new Promise((resolve) => {
      // 复制npc到Merchant.txt
      // const str = fs.readFileSync(path.join(config.path2, '步骤1', 'npc.txt')).toString();
      const str = config.npcText;
      let newContent = str.replace(new RegExp('主城代码', 'g'), config.zhucheng_code);
      api.copePath(newContent)
      api.openFile(config, 'Merchant.txt')

      // // 目标文件
      // const filePath = path.join(config.path1, "Mir200", 'Envir', 'Merchant.txt');
      // // 要添加的内容
      // const contentToAdd = `${newContent}\n`;
      // // 读取原有文件内容
      // const str2 = fs.readFileSync(filePath);
      // const content = iconv.decode(str2, 'GBK');
      // // 在文件内容后面添加新内容
      // const newData = contentToAdd + content;
      // console.log(newData, 'newData')
      // // 写入新内容到文件
      // fun(filePath, newData, false)

      resolve(true)
    })
  },
  huiyuan3: (config) => {
    return new Promise((resolve) => {
      if (config.path1 !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, "步骤3", '放进qu里');
        // 目标文件夹
        const destinationFolder = path.join(config.path1, "Mir200", 'Envir', 'QuestDiary');

        // 先删除
        // setTimeout(() => {
        // 在复制
        copyFiles(sourceFolder, destinationFolder)
        // }, 1000)

        resolve(true)
      }
      resolve(false)
      // fs.rename(pathToFile, newPathToFile, function () { })
    })
  },
  huiyuan4: (config) => {
    return new Promise((resolve) => {
      if (config.path2 !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, '通区文件(放入根目录)');
        // 目标文件夹
        const destinationFolder = path.dirname(config.path1);

        // 复制
        copyFiles(sourceFolder, destinationFolder)

        resolve(true)
      }
      resolve(false)
    })
  },
  gongsha: (config) => {
    return new Promise((resolve) => {
      if (config.zhucheng_code !== '') {
        // 源文件夹
        const p = path.join(config.path2, "攻沙脚本", '攻沙脚本全套')
        const sourceFolder = path.join(p, '攻城传送-主城代码.txt');
        const sourceFolder2 = path.join(p, '沙城领奖员-主城代码.txt');
        // 目标文件夹
        const p1 = path.join(config.path1, "Mir200", 'Envir', 'Market_Def')
        const destinationFolder = path.join(p1, '攻城传送-主城代码.txt');
        const destinationFolder2 = path.join(p1, '沙城领奖员-主城代码.txt');

        // 先删除
        if (lastZhucheng_code) {
          fs.unlinkSync(path.join(p1, `攻城传送-${lastZhucheng_code}.txt`))
          fs.unlinkSync(path.join(p1, `沙城领奖员-${lastZhucheng_code}.txt`))
        }
        
        fs.copyFile(sourceFolder, destinationFolder, (err) => {
          fs.rename(destinationFolder, destinationFolder.replace(`主城代码.txt`, `${config.zhucheng_code}.txt`), () => {})
        })
        fs.copyFile(sourceFolder2, destinationFolder2, ()=>{
          fs.rename(destinationFolder2, destinationFolder2.replace(`主城代码.txt`, `${config.zhucheng_code}.txt`), () => {})
        })

        lastZhucheng_code = config.zhucheng_code

        resolve(true)
      }
      // fs.rename(pathToFile, newPathToFile, function () { })
    })
  },
  huiyuan_new1: (config) => {
    return new Promise((resolve) => {
      if (config.zhucheng_code !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, 'newConfig', '版本脚本安装', 'Envir', 'Market_Def', '37W功能w');
        // 目标文件夹
        const destinationFolder = path.join(config.path1, "Mir200", 'Envir', 'Market_Def');

        // 先删除
        deleteFolder(path.join(destinationFolder, '37W功能'))
        copyFiles(sourceFolder, destinationFolder)

        setTimeout(() => {
          // 修改文件名中的主城代码
          const files = glob.globSync(destinationFolder + `/**/*-主城代码.txt`, {});
          files.forEach(function (file) {
            fs.rename(file, file.replace(`主城代码.txt`, `${config.zhucheng_code}.txt`), function () { })
          });
        }, 1500)

        resolve(true)
      }
      resolve(false)
    })
  },
  huiyuan_new2: (config) => {
    return new Promise((resolve) => {
      if (config.path1 !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, "newConfig", "版本脚本安装", "Envir", "QuestDiary");
        // 目标文件夹
        const destinationFolder = path.join(config.path1, "Mir200", 'Envir', 'QuestDiary');

        // 先删除
        deleteFolder(path.join(destinationFolder, '37W通服功能'))
        deleteFolder(path.join(destinationFolder, '游戏币明细'))

        setTimeout(() => {
          // 在复制
          copyFiles(sourceFolder, destinationFolder)
        }, 500)

        resolve(true)
      }
      resolve(false)
    })
  },
  huiyuan_new3: (config) => {
    return new Promise((resolve) => {
      if (!config.path1) {
        return resolve(false)
      }
      if (config.path1 !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, "newConfig", "版本脚本安装", "dll");
        // 目标文件夹
        const destinationFolder = path.join(config.path1, "Mir200");
        // 在复制
        copyFiles(sourceFolder, destinationFolder)
        resolve(true)
      }
      resolve(false)
    })
  },
  huiyuan_new4: (config) => {
    return new Promise((resolve) => {
      if (config.path1 !== '') {
        // 源文件夹
        const sourceFolder = path.join(config.path2, 'newConfig', '根目录存放');
        // 目标文件夹
        const destinationFolder = path.dirname(config.path1);

        // 复制
        copyFiles(sourceFolder, destinationFolder)

        resolve(true)
      }
      resolve(false)
    })
  },
  openCZ: (config) => {
    if (config.path1 !== '') {
      api.openFile(config, 'QuestDiary', '37W通服功能', '充值脚本.txt')
    }
  },
  lookup: (config) => {
    return new Promise((resolve) => {
      if (!config.versionPath || !config.path) {
        return resolve(false)
      }
      // 递归搜索文件夹中所有文本文件，并替换文本内容
      const files = glob.globSync(`${config.versionPath}/**/*.txt`, {});

      const obj: any = []
      files.forEach(function (file, i) {
        // 读取文件内容
        let data = fs.readFileSync(file);
        // 将文本内容进行替换

        const encoding = jschardet.detect(data).encoding;
        let content = ''
        if (encoding === 'GB2312') {
          content = iconv.decode(data, 'GBK');
        } else {
          content = data.toString()
        }
        fs.chmodSync(file, '700'); // 修改成全员读写权限


        var regex = /(?<!;\s*)\bADDBUTTON\b\s+(\S+)\s+(\S+)/g; // 匹配每个ADDBUTTON后面的两个由空格隔开的字符串
        var matches = content.match(regex);

        if (matches) {
          // matches数组将包含所有匹配的结果，每个匹配是一个数组，其中包含三个元素：整个匹配、第一个捕获组和第二个捕获组
          // 我们只关心每个匹配中的第二个捕获组（即第二个字符串）
          var buttonList = matches.map(match => {
            return {
              context: match,
              val: match.match(/(?<!;\s*)\bADDBUTTON\b\s+(\S+)\s+(\S+)/)?.[2]
            }
          });
          obj.push({
            file,
            buttonList
          })
        }
      })

      let arr: any = []
      obj.forEach(item => {
        const d = item.buttonList.map(_ => _.val);
        arr = [...arr, ...d]
      })
      obj[0].tongji = [...new Set(arr)].sort((a: any, b: any) => {
        // 检查a和b是否都是数字字符串
        const isNumericA = /^\d+$/.test(a);
        const isNumericB = /^\d+$/.test(b);

        // 如果a和b都是数字字符串，则进行数值比较
        if (isNumericA && isNumericB) {
          return a - b; // 数值比较，返回差值
        }

        // 如果a是数字而b不是，则a应该在b之前
        if (isNumericA) {
          return -1;
        }

        // 如果b是数字而a不是，则b应该在a之前
        if (isNumericB) {
          return 1;
        }

        // 如果a和b都不是数字字符串，则它们的顺序不变
        return 0;
      });
      resolve(obj)
    })
  },
  fileTH: (_path) => {
    return new Promise((resolve) => {
      const p1 = path.dirname(_path); // 获取上一级
      const list: any[] = []
      fs.readdirSync(p1).forEach(file => {
        if (file.includes(path.basename(_path))) {
          list.push(file)
        }
      });
      resolve({
        url: p1,
        list: list.map(item => {
          return {
            label: path.join(p1, item),
            value: path.join(p1, item),
          }
        }),
      })
    })
  },
  fileTH2: (modifyFile, value, onSuccess, onError) => {
    try {
      modifyFile.forEach(function (item) {
        const p1 = item?.originFileObj?.path
        value.forEach((item2) => {
          const p2 = path.join(item2, 'Mir200', p1.split('Mir200')[1])

          try {
            fs.chmodSync(p2, '700'); // 修改成全员读写权限
          } catch (err: any) {
            if (err.code === 'ENOENT') {
              console.error('文件不存在');
            }
          }

          // 读取文件内容
          let data = fs.readFileSync(p1);
          // const encoding = jschardet.detect(data).encoding;
          // let content = ''
          // if (encoding === 'GB2312') {
          //   content = iconv.decode(data, 'GBK');
          // } else {
          //   content = data.toString()
          // }
          // fs.writeFileSync(p2, encoding === 'GB2312' ? iconv.encode(content, 'GBK') : content);


          let content = iconv.decode(data, 'GBK')
          fs.writeFileSync(p2, iconv.encode(content, 'GBK'));
        })
      });
      onSuccess()
    } catch (error: any) {
      onError(error)
    }
  },
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
